#!/usr/bin/env python3.11
# -*- coding: utf-8 -*-
"""
股票分析脚本 - 遍历CSV文件中的股票代码，进行MACD分析
筛选出quality_score大于80分的股票并记录到日志文件
"""

import csv
import requests
import json
from datetime import datetime
import time
import os
from concurrent.futures import ThreadPoolExecutor
import threading
import logging
import markdown
# 已移除PDF相关导入
import re

# 已移除中文字体注册，使用系统默认字体

def get_report_filename():
    """生成报告文件名"""
    current_date = datetime.now().strftime("%Y%m%d")
    # 获取脚本所在目录的上级目录，然后定位到result目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    result_dir = os.path.join(os.path.dirname(script_dir), "result")
    os.makedirs(result_dir, exist_ok=True)
    return os.path.join(result_dir, f"{current_date}.txt")

# 已移除get_pdf_filename函数

def setup_logging():
    """设置日志记录"""
    current_date = datetime.now().strftime("%Y%m%d")
    # 获取脚本所在目录，然后定位到log目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    log_dir = os.path.join(script_dir, "log")
    os.makedirs(log_dir, exist_ok=True)
    log_filename = os.path.join(log_dir, f"{current_date}_analysis.log")
    
    # 配置日志格式
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(log_filename, encoding='utf-8')
        ]
    )
    
    return logging.getLogger(__name__)

def read_stock_codes(csv_file_path):
    """读取CSV文件中的股票代码"""
    stock_codes = []
    try:
        with open(csv_file_path, 'r', encoding='utf-8-sig') as file:
            reader = csv.DictReader(file)
            for row in reader:
                code = row['代码'].strip()
                name = row['名称'].strip()
                stock_codes.append({'code': code, 'name': name})
        return stock_codes
    except Exception as e:
        # 不在控制台输出错误信息
        return []

def analyze_stock_batch(stock_codes_batch):
    """批量分析股票（同时处理5个）"""
    results = []
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        # 创建所有请求的future
        futures = []
        for stock in stock_codes_batch:
            future = executor.submit(analyze_single_stock, stock)
            futures.append((future, stock))
        
        # 收集结果
        for future, stock in futures:
            try:
                result = future.result(timeout=30)
                if result:
                    results.append((stock, result))
            except Exception as e:
                pass
    
    return results

def analyze_single_stock(stock):
    """
    分析单个股票 - 使用增强分析API接口
    """
    code = stock['code']
    name = stock['name']
    # 优先使用增强分析接口
    url = f"http://localhost:5001/api/enhanced-analyze/{code}"
    
    logger = logging.getLogger(__name__)
    
    try:
        logger.info(f"开始增强分析股票: {code} ({name})")
        response = requests.get(url, timeout=15)
        response.raise_for_status()
        
        result = response.json()
        
        # 记录完整的API响应到日志
        logger.info(f"股票 {code} ({name}) 增强API响应状态: {response.status_code}")
        
        # 如果有分析结果，记录关键信息
        if result and result.get('status') == 'success':
            data = result.get('data', {})
            enhanced_recommendation = data.get('enhanced_recommendation', {})
            macd_analysis = data.get('macd_analysis', {})
            rsi_analysis = data.get('rsi_analysis', {})
            detailed_scores = data.get('detailed_scores', {})
            
            # 获取增强分析的关键指标
            total_score = enhanced_recommendation.get('total_score', 0)
            win_probability = enhanced_recommendation.get('win_probability', 0)
            position_ratio = enhanced_recommendation.get('position_ratio', 0)
            risk_level = enhanced_recommendation.get('risk_level', 'unknown')
            
            # 获取传统MACD指标
            quality_score = macd_analysis.get('quality_score', 0)
            timeliness_score = macd_analysis.get('timeliness_score', 0)
            golden_cross_detected = macd_analysis.get('golden_cross_detected', False)
            death_cross_detected = macd_analysis.get('death_cross_detected', False)
            death_cross_risk_level = macd_analysis.get('death_cross_risk_level', 'low')
            
            # RSI信息
            rsi_value = rsi_analysis.get('current_rsi', 0)
            rsi_status = rsi_analysis.get('status', '未知')
            
            logger.info(f"股票 {code} ({name}) 增强分析结果:")
            logger.info(f"  - 综合评分: {total_score}/100")
            logger.info(f"  - 胜率预测: {win_probability}%")
            logger.info(f"  - 建议仓位: {position_ratio}%")
            logger.info(f"  - 风险等级: {risk_level}")
            logger.info(f"  - MACD质量评分: {quality_score}/100")
            logger.info(f"  - 时效评分: {timeliness_score}/100")
            logger.info(f"  - RSI值: {rsi_value} ({rsi_status})")
            logger.info(f"  - 金叉: {golden_cross_detected}, 死叉: {death_cross_detected}")
            
            if death_cross_detected:
                logger.warning(f"股票 {code} ({name}) 检测到死叉信号，风险等级: {death_cross_risk_level}")
        else:
            logger.warning(f"股票 {code} ({name}) 增强分析失败或无数据")
        
        return result
        
    except requests.exceptions.Timeout:
        logger.error(f"股票 {code} ({name}) 请求超时")
        return None
    except requests.exceptions.RequestException as e:
        logger.error(f"股票 {code} ({name}) 请求异常: {e}")
        return None
    except json.JSONDecodeError as e:
        logger.error(f"股票 {code} ({name}) JSON解析错误: {e}")
        return None
    except Exception as e:
        logger.error(f"股票 {code} ({name}) 分析异常: {e}")
        return None

def process_batch_results(batch_results, high_quality_stocks):
    """
    处理批量分析结果 - 适配增强分析API
    """
    found_count = 0
    logger = logging.getLogger(__name__)
    
    for stock, result in batch_results:
        if not result or result.get('status') != 'success':
            logger.warning(f"股票 {stock['code']} ({stock['name']}) 无有效分析结果")
            continue
        
        data = result.get('data', {})
        enhanced_recommendation = data.get('enhanced_recommendation', {})
        macd_analysis = data.get('macd_analysis', {})
        rsi_analysis = data.get('rsi_analysis', {})
        detailed_scores = data.get('detailed_scores', {})
        
        # 获取增强分析指标
        total_score = enhanced_recommendation.get('total_score', 0)
        win_probability = enhanced_recommendation.get('win_probability', 0)
        position_ratio = enhanced_recommendation.get('position_ratio', 0)
        hold_period = enhanced_recommendation.get('hold_period', '')
        risk_level = enhanced_recommendation.get('risk_level', 'unknown')
        action_text = enhanced_recommendation.get('action_text', '')
        
        # 获取传统MACD指标
        quality_score = macd_analysis.get('quality_score', 0)
        position_score = macd_analysis.get('position_score', 0)
        resonance_score = macd_analysis.get('resonance_score', 0)
        volume_score = macd_analysis.get('volume_score', 0)
        timeliness_score = macd_analysis.get('timeliness_score', 0)
        
        golden_cross_detected = macd_analysis.get('golden_cross_detected', False)
        golden_cross_date = macd_analysis.get('golden_cross_date', '')
        death_cross_detected = macd_analysis.get('death_cross_detected', False)
        death_cross_date = macd_analysis.get('death_cross_date', '')
        death_cross_risk_level = macd_analysis.get('death_cross_risk_level', 'low')
        death_cross_risk_score = macd_analysis.get('death_cross_risk_score', 0)
        
        # RSI数据
        rsi_value = rsi_analysis.get('current_rsi', 0)
        rsi_status = rsi_analysis.get('status', '')
        
        # 记录所有股票的分析结果摘要
        logger.info(f"股票 {stock['code']} ({stock['name']}) 增强分析结果:")
        logger.info(f"  - 综合评分: {total_score:.1f}/100")
        logger.info(f"  - 胜率预测: {win_probability:.1f}%")
        logger.info(f"  - 建议仓位: {position_ratio:.1f}%")
        logger.info(f"  - 持有时间: {hold_period}")
        logger.info(f"  - 风险等级: {risk_level}")
        logger.info(f"  - MACD质量评分: {quality_score:.1f}/100")
        logger.info(f"  - 位置评分: {position_score:.1f}/100")
        logger.info(f"  - 共振评分: {resonance_score:.1f}/100")
        logger.info(f"  - 量能评分: {volume_score:.1f}/100")
        logger.info(f"  - 时效评分: {timeliness_score:.1f}/100")
        logger.info(f"  - RSI值: {rsi_value:.1f} ({rsi_status})")
        logger.info(f"  - 金叉状态: {'✅ 检测到' if golden_cross_detected else '❌ 未检测到'}")
        if golden_cross_detected:
            logger.info(f"  - 金叉日期: {golden_cross_date}")
        
        if death_cross_detected:
            logger.warning(f"  - 死叉状态: ⚠️ 检测到 (日期: {death_cross_date})")
            logger.warning(f"  - 死叉风险等级: {death_cross_risk_level.upper()} ({death_cross_risk_score:.1f}/100)")
        
        logger.info(f"  - 投资建议: {action_text}")
        
        # 高质量股票筛选条件（优化标准）：
        # 主要筛选条件：
        # 1. 综合评分 > 80 且胜率 > 70%
        # 2. 建议仓位 > 20% (保持仓位要求)
        # 3. RSI < 60 (适度放宽超买限制)
        # 4. 没有高风险死叉
        
        # 筛选条件：评分和胜率都大于80分
        is_high_quality = (
            total_score > 80 and
            win_probability > 80 and
            position_ratio > 20 and
            rsi_value < 60 and
            not (death_cross_detected and death_cross_risk_level == 'high')
        )
        
        if is_high_quality:
            high_quality_info = {
                'code': stock['code'],
                'name': stock['name'],
                'symbol': data.get('symbol', stock['code']),
                # 增强分析数据
                'total_score': total_score,
                'win_probability': win_probability,
                'position_ratio': position_ratio,
                'hold_period': hold_period,
                'risk_level': risk_level,
                'action_text': action_text,
                # 传统MACD数据
                'quality_score': quality_score,
                'position_score': position_score,
                'resonance_score': resonance_score,
                'volume_score': volume_score,
                'timeliness_score': timeliness_score,
                'golden_cross_detected': golden_cross_detected,
                'golden_cross_date': golden_cross_date,
                'death_cross_detected': death_cross_detected,
                'death_cross_date': death_cross_date,
                'death_cross_risk_level': death_cross_risk_level,
                'death_cross_risk_score': death_cross_risk_score,
                # 其他数据
                'current_price': data.get('price_info', {}).get('current_price', 0),
                'price_change_percent': data.get('price_info', {}).get('price_change_percent', 0),
                'analysis_date': data.get('analysis_date', ''),
                'rsi_value': rsi_value,
                'rsi_status': rsi_status,
                # 详细评分（适配新的权重体系）
                'macd_score': detailed_scores.get('macd_score', 0),
                'rsi_score': detailed_scores.get('rsi_score', 0),
                'trend_score': detailed_scores.get('trend_score', 0),
                'momentum_score': detailed_scores.get('momentum_score', 0),
                'volatility_score': detailed_scores.get('volatility_score', 0),
                'drawdown_risk_score': detailed_scores.get('drawdown_risk_score', 50),  # 新增回撤风险评分
                'support_resistance_score': detailed_scores.get('support_resistance_score', 0),
                'market_environment_score': detailed_scores.get('market_environment_score', 0),
                'valuation_score': detailed_scores.get('valuation_score', 0),
                'death_to_golden_bonus': detailed_scores.get('death_to_golden_bonus', 0)  # 新增死叉到金叉奖励评分
            }
            
            high_quality_stocks.append(high_quality_info)
            found_count += 1
            
            # 标记股票类型
            stock_type = "高质量"
            
            logger.info(f"🌟 发现{stock_type}股票: {stock['code']} ({stock['name']}) - 综合评分: {total_score:.1f}, 胜率: {win_probability:.1f}%, 仓位: {position_ratio:.1f}%, RSI: {rsi_value:.1f}")
            pass
            
            # 添加股票类型标记
            high_quality_info['stock_type'] = stock_type
    
    return found_count

def generate_markdown_report(high_quality_stocks, report_filename, total_stocks, total_analyzed):
    """
    生成简化版Markdown格式报告 - 只包含股票列表和生成时间
    """
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    with open(report_filename, 'w', encoding='utf-8') as f:
        # 只写入股票列表表格
        if high_quality_stocks:
            # 按total_score降序排列
            high_quality_stocks.sort(key=lambda x: x['total_score'], reverse=True)
            
            f.write(f"| 排名 | 类型 | 股票代码 | 股票名称 | 综合评分 | 胜率预测 | 建议仓位 | 持有时间 | 风险等级 | 投资建议 | 当前价格 | 涨跌幅 |\n")
            f.write(f"|------|------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|\n")
            
            for i, stock in enumerate(high_quality_stocks, 1):
                price_change = f"{stock['price_change_percent']:+.2f}%" if stock['price_change_percent'] else "--"
                current_price = f"¥{stock['current_price']}" if stock['current_price'] else "--"
                
                risk_emoji = {'low': '🟢', 'medium': '🟡', 'high': '🔴'}.get(stock['risk_level'], '❔')
                
                # 股票类型显示
                stock_type_emoji = "🎯"
                stock_type_text = "高质量"
                
                f.write(f"| {i} | {stock_type_emoji}{stock_type_text} | `{stock['code']}` | {stock['name']} | **{stock['total_score']:.1f}** | **{stock['win_probability']:.1f}%** | **{stock['position_ratio']:.1f}%** | {stock['hold_period']} | {risk_emoji}{stock['risk_level']} | {stock['action_text']} | {current_price} | {price_change} |\n")
        
        # 在文件末尾添加生成时间
        f.write(f"\n@{datetime.now().strftime('%Y%m%d')}.txt  @{current_time}\n")

# 已移除generate_pdf_report函数

def main():
    """主函数 - 增强分析版本"""
    # 设置日志记录
    logger = setup_logging()
    
    # 显示算法优化信息
    pass
    
    pass
    logger.info("开始优质股票分析（优化权重评分体系 + 并发处理）")
    
    # 生成报告文件名
    report_filename = get_report_filename()
    
    # CSV文件路径
    csv_file_path = "ashares_full.csv"
    
    # 检查CSV文件是否存在
    if not os.path.exists(csv_file_path):
        error_msg = f"CSV文件不存在: {csv_file_path}"
        pass
        logger.error(error_msg)
        return
    
    # 读取股票代码
    pass
    logger.info("开始读取股票代码")
    stock_codes = read_stock_codes(csv_file_path)
    
    if not stock_codes:
        error_msg = "未能读取到股票代码"
        logger.error(error_msg)
        return
    
    success_msg = f"成功读取 {len(stock_codes)} 个股票代码"
    pass
    logger.info(success_msg)
    pass
    logger.info(f"报告将保存到: {report_filename}")
    pass
    
    # 存储高质量股票的列表
    high_quality_stocks = []
    
    # 统计信息
    total_analyzed = 0
    high_quality_count = 0
    batch_size = 5
    
    try:
        # 将股票代码分批处理，每批20个
        for i in range(0, len(stock_codes), batch_size):
            batch = stock_codes[i:i + batch_size]
            batch_num = i // batch_size + 1
            total_batches = (len(stock_codes) + batch_size - 1) // batch_size
            
            batch_msg = f"处理第 {batch_num}/{total_batches} 批 ({len(batch)} 个股票)"
            pass
            logger.info(batch_msg)
            
            # 记录当前批次的股票列表
            batch_stocks = [f"{s['code']}({s['name']})" for s in batch]
            logger.info(f"第 {batch_num} 批股票列表: {', '.join(batch_stocks)}")
            
            # 并发分析这一批股票
            batch_results = analyze_stock_batch(batch)
            total_analyzed += len(batch)
            
            # 处理这一批的结果
            found_in_batch = process_batch_results(batch_results, high_quality_stocks)
            high_quality_count += found_in_batch
            
            batch_complete_msg = f"第 {batch_num} 批完成，本批发现 {found_in_batch} 个高质量股票"
            progress_msg = f"当前进度: {total_analyzed}/{len(stock_codes)}，累计发现 {high_quality_count} 个高质量股票"
            
            # 移除所有打印语句，只保留日志记录
            pass
            pass
            logger.info(batch_complete_msg)
            logger.info(progress_msg)
            pass
            
            # 批次间稍作休息
            time.sleep(1)
    
    except KeyboardInterrupt:
        interrupt_msg = "用户中断了分析过程"
        pass
        logger.warning(interrupt_msg)
    
    # 生成Markdown报告
    pass
    logger.info("开始生成Markdown报告")
    generate_markdown_report(high_quality_stocks, report_filename, len(stock_codes), total_analyzed)
    logger.info(f"Markdown报告已生成: {report_filename}")
    
    # 已移除PDF报告生成部分
    
    # 输出最终统计
    pass
    final_msg = "分析完成！"
    pass
    logger.info(final_msg)
    
    summary_stats = {
        "总股票数量": len(stock_codes),
        "已分析数量": total_analyzed,
        "优质股票数": high_quality_count,
        "报告文件": report_filename
    }
    
    pass
    pass
    pass
    pass
    
    logger.info(f"最终统计: {json.dumps(summary_stats, ensure_ascii=False)}")
    
    if high_quality_stocks:
        pass
        logger.info("优质股票详细列表:")
        
        high_quality_stocks.sort(key=lambda x: x['total_score'], reverse=True)
        
        # 记录所有优质股票到日志
        for i, stock in enumerate(high_quality_stocks, 1):
            stock_detail = f"排名{i}: {stock['code']}({stock['name']}) - 综合评分: {stock['total_score']:.1f}, 胜率: {stock['win_probability']:.1f}%, 仓位: {stock['position_ratio']:.1f}%, 风险: {stock['risk_level']}, 金叉: {'是' if stock['golden_cross_detected'] else '否'}, 死叉风险: {stock['death_cross_risk_level'] if stock['death_cross_detected'] else '无'}, 投资建议: {stock['action_text']}"
            logger.info(stock_detail)
        
        # 控制台显示前5个
        pass
        pass
    else:
        no_result_msg = "本次优化权重分析未发现符合条件的优质股票"
        logger.info(no_result_msg)

if __name__ == "__main__":
    main()